package com.mainbo.androidframework.utils;

import android.content.Context;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author wei
 *         <b>创建时间</b> 2015/10/18
 */
public class AssetsUtils {

    /**
     * copy assets 下的文件到sd卡
     *
     * @param context context
     * @param path    path
     */
    public static void copyToSdcard(Context context, String path, String targetPath) {
        try {
            String str[] = context.getAssets().list(path);
            if (str.length > 0) {//如果是目录
                File file = new File(targetPath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                for (String string : str) {
                    path = path + "/" + string;
                    targetPath = targetPath + "/" + string;
                    copyToSdcard(context, path, targetPath);
                    path = path.substring(0, path.lastIndexOf('/'));
                    targetPath = targetPath.substring(0, targetPath.lastIndexOf('/'));
                }
            } else {//如果是文件
                InputStream is = context.getAssets().open(path);
                File file = new File(targetPath);
                if (file.exists()) {
                    file.delete();
                }
                file.createNewFile();
                FileOutputStream fos = new FileOutputStream(new File(targetPath));
                byte[] buffer = new byte[1024];
                int count = 0;
                while (true) {
                    count++;
                    int len = is.read(buffer);
                    if (len == -1) {
                        break;
                    }
                    fos.write(buffer, 0, len);
                }

                is.close();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
